import datetime
from django.shortcuts import redirect, HttpResponse, render
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from django.forms import model_to_dict
from utils.encrypt import md5
from web import models


class Tracer(object):

    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None
        self.wiki = None
        self.rdstr = None


class AuthMiddleware(MiddlewareMixin):

    def process_request(self, request):

        request.tracer = Tracer()

        user_id = request.session.get('user_id', 0)
        user_object = models.UserInfo.objects.filter(id=user_id).first()
        request.tracer.user = user_object
        request.tracer.rdstr = md5(str(request.tracer.user))  # 删除携带随机字符串

        # PATH过滤
        if request.path in settings.WHITE_REGEX_URL_LIST:
            return None

        if not request.tracer.user:
            return HttpResponse('''
            <script> 
                alert("请先登录");location.href = "http://127.0.0.1:8000/login/"
            </script>
            ''')

        # 登录成果后，携带用户所拥有的额度
        if request.path != "/logout/":
            _object = models.Transaction.objects.filter(user=user_object).order_by('-id').first()
            if _object.end_datetime and _object.end_datetime < datetime.datetime.now():
                _object = models.Transaction.objects.filter(user=user_object, status=2,
                                                            price_policy__category=1).first()
            request.tracer.price_policy = _object.price_policy
            # print(type(_object), type(_object.price_policy))
            # print(_object.price_policy, _object)
            # print(model_to_dict(_object.price_policy), model_to_dict(_object))

    def process_view(self, request, view, args, kwargs):

        #  判断url是否以manage开头，且项目id是否是我参与or创建的
        if not request.path_info.startswith('/manage/'):
            return

        project_id = kwargs.get('project_id')

        # 是否是我创建的
        project_object = models.Project.objects.filter(creator=request.tracer.user, id=project_id).first()
        if project_object:
            request.tracer.project = project_object
            return

        # 是否是我参与的
        project_user_object = models.ProjectUser.objects.filter(user=request.tracer.user, project_id=project_id).first()
        if project_user_object:
            request.tracer.project = project_user_object.project
            return

        return render(request, 'manage_error.html', {'return_url': '/project/list/'})


class PreviousURLMiddleware(MiddlewareMixin):
    """ 获取上一次访问的url """
    def process_response(self, request, response):
        if response.status_code == 200:
            request.session['previous_url'] = request.get_full_path()
        return response


class DeleteMiddleware(MiddlewareMixin):

    def process_request(self, request):
        if 'delete' in request.path:
            last_manage_id = request.session['previous_url'].split('/')[2]
            if request.path.split('/')[2] != last_manage_id:
                return render(request, 'manage_error.html', {'return_url': '/manage/{}/file'.format(last_manage_id)})

